package zoo.member.admin.controller;


import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import zoo.member.admin.dao.AdminDao;
import zoo.member.admin.domain.AdminCommand;
import zoo.member.admin.validator.AdminLoginValidator;

@Controller
public class AdminLoginController {
	@Autowired
	private AdminDao adminDao;
	private String formViewName = "loginform";
	private static Log log = LogFactory.getLog(AdminLoginController.class);
	
	@RequestMapping(value="/admin/loginform.do",method=RequestMethod.GET)
	public String form() {
			return formViewName;
	}
	
	@ModelAttribute("command")
	public AdminCommand formBacking(){
		return new AdminCommand();
	}
	
	@RequestMapping(value="/admin/loginform.do",method=RequestMethod.POST)
	public String submit(@ModelAttribute("command")AdminCommand adminCommand,
							BindingResult result, HttpServletRequest request, HttpServletResponse response) throws IOException{
		
		new AdminLoginValidator().validate(adminCommand,result);
				
		if(result.hasErrors()){
			return formViewName;
		}
		
		if(log.isDebugEnabled()){
			log.debug("id : "+adminCommand.getMa_name()+", Grade : "+ adminCommand.getMa_grade());
		}
		
		AdminCommand admin = adminDao.selectAdmin(adminCommand.getMa_name()); 
				
		if(admin !=  null && adminCommand.getMa_passwd().equals(admin.getMa_passwd())){
			
			//세션에 아이디를 저장
			HttpSession session = request.getSession();
			session.setAttribute("ma_name", adminCommand.getMa_name());
				
			return "admin_index";
			
		}else{
			//아아디 또는 비번이 일치하지 않음
			result.reject("invalidIdOrPassword",new Object[]{adminCommand.getMa_name()},null);
				
			return "loginform";
	
		}
	}	
}
